#!/bin/bash -x

kernel_local_version="-openanolis"
kernel_repo_url="https://gitee.com/anolis/cloud-kernel.git"
kernel_repo_branch="devel-6.6"
kernel_repo_commit="ab224dde9d0e07d1aa69f26c2b3b63b3b37004f5"
kernel_repo_dir="/dev/shm/openanolis-kernel"

kernel_revert_commits=( \
  "ad91a2dacbf8c26a446658cdd55e8324dfeff1e7"
  )

if [ ! -e ${kernel_repo_dir} ]; then
  git clone ${kernel_repo_url} \
    -b ${kernel_repo_branch} \
    ${kernel_repo_dir}
fi
pushd ${kernel_repo_dir}
git reset --hard ${kernel_repo_commit}
# It's suggested to revert some commits to support kata & coco under anolis linux-6.6
git config user.email "kata-coco-builder" && \
git config user.name "kata-coco-builder"
for commit in ${kernel_revert_commits[@]}; do
  git diff ${commit} ${commit}~1 > patch.diff.revert.${commit}
  git apply patch.diff.revert.${commit}
  git status | grep modified: | awk '{print $2}' | xargs -n1 git add
  git status | grep deleted: | awk '{print $2}' | xargs -n1 git rm
  git status -s | grep "^??" | awk '{print $2}' | xargs -n1 git add
  git commit -s -m "revert ${commit}"
done
popd # ${kernel_repo_dir}

install_host_kernel_deps () {
  echo "[Install host kernel dependencies]"
  sudo yum install -y bc openssl rsync
  sudo yum install -y \
    make gcc gcc-c++ \
    flex bison openssl-devel \
    elfutils-libelf-devel \
    ncurses-devel \
    rpm-build perl dwarves
}

install_host_kernel_deps

build_host_kernel () {
  echo "[Build host kernel]"

  pushd ${kernel_repo_dir}
  make anolis_defconfig
  make binrpm-pkg -j$(nproc --ignore=2) LOCALVERSION="${kernel_local_version}"
  popd # ${kernel_repo_dir}
}

build_host_kernel
